package org.fall.service.impl;

import org.entity.Admin;
import org.entity.AdminExample;
import org.fall.constant.CrowdConstant;
import org.fall.exeception.LoginAcctAlreadyInUseException;
import org.fall.exeception.LoginFailedException;
import org.fall.mapper.AdminMapper;
import org.fall.service.AdminService;
import org.fall.util.CrowdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public void saveAdmin(Admin admin) {
        //生成系统时间
        Date date = new Date();
        // 格式化时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createTime = simpleDateFormat.format(date);
        // 设置管理员创建时间
        admin.setCreateTime(createTime);
        String source = admin.getUserPswd();
        // 得到前端传入的密码，加密并放回原本的admin对象
        String encode = passwordEncoder.encode(source);
//        String encode = CrowdUtil.md5(source);

        admin.setUserPswd(encode);
        // 执行插入操作
        try {
            adminMapper.insert(admin);
        } catch (Exception e) {
            e.printStackTrace();
            // 这里出现异常的话一般就是DuplicateKeyException（因为插入的loginAcct已存在而触发）
            if (e instanceof DuplicateKeyException) {
                // 如果确实是DuplicateKeyException，此时抛出一个自定义的异常
                throw new LoginAcctAlreadyInUseException(CrowdConstant.MESSAGE_SYSTEM_ERROR_LOGIN_NOT_UNIQUE);
            }
        }
    }

    @Override
    public List<Admin> getAll() {
        return adminMapper.selectByExample(new AdminExample());
    }

    @Override
    public Admin getAdminByLoginAcct(String loginUser, String loginPwd) {
        // 1、根据登陆账号查询Admin对象

        // 创建AdminExample对象
        AdminExample adminExample = new AdminExample();

        // 创建Criteria对象
        AdminExample.Criteria criteria = adminExample.createCriteria();
        // 在Criteria对象中封装查询的条件
        criteria.andLoginAcctEqualTo(loginUser);
        // 调用AdminMapper的方法来查询
        List<Admin> admins = adminMapper.selectByExample(adminExample);
        // 2、判断Admin对象是否为null或数据库数据不正常
        if (admins == null || admins.size() == 0) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }
        if (admins.size() > 1) {
            throw new RuntimeException(CrowdConstant.MESSAGE_SYSTEM_ERROR_LOGIN_NOT_UNIQUE);
        }
        // 前面判断完后无异常，取出admin对象
        // 3、如果Admin对象为null 则抛出异常
        Admin admin = admins.get(0);
        if (admin == null) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }
        // 4、如果Admin对象不为null，则取出Admin对象的密码
        String userPswdDb = admin.getUserPswd();
        // 5、对表单提交的密码进行md5加密
        String userPswdFrom = CrowdUtil.md5(loginPwd);
        // 6、对比两个密码
        // 因为两个密码都是对象，使用字符串的equals方法，如果存在空的密码则会触发空指针异常
        // 因此选用Objects.equals方法
        if (!Objects.equals(userPswdDb, userPswdFrom)) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }
        // 7、比对结果一致，返回admin对象
        return admin;
    }

    @Override
    public Admin getAdminByLoginAccts(String loginUser) {
        AdminExample adminExample = new AdminExample();
        AdminExample.Criteria criteria = adminExample.createCriteria();
        criteria.andLoginAcctEqualTo(loginUser);
        List<Admin> list = adminMapper.selectByExample(adminExample);
        Admin admin = list.get(0);
        return admin;
    }

    @Override
    public List<Admin> getPageInfoByKeyword(String keyword) {
        return adminMapper.selectByKeyword(keyword);
    }

    @Override
    public void removeAdmin(Integer adminId) {
        adminMapper.deleteByPrimaryKey(adminId);
    }

    @Override
    public Admin getAllByAdminId(Integer adminId) {
        return adminMapper.selectByPrimaryKey(adminId);
    }

    @Override
    public void update(Admin admin) {
        // 执行插入操作
        try {
            adminMapper.updateByPrimaryKeySelective(admin);
        } catch (Exception e) {
            e.printStackTrace();
            // 这里出现异常的话一般就是DuplicateKeyException（因为插入的loginAcct已存在而触发）
            if (e instanceof DuplicateKeyException) {
                // 如果确实是DuplicateKeyException，此时抛出一个自定义的异常
                throw new LoginAcctAlreadyInUseException(CrowdConstant.MESSAGE_SYSTEM_ERROR_LOGIN_NOT_UNIQUE);
            }
        }
    }

    @Override
    public void saveAdminRoleRelationship(Integer adminId,  List<Integer> roleIdList) {

        // 先清除旧的对应inner_admin_role表中对应admin_id的数据
        adminMapper.clearOldRelationship(adminId);

        // 如果roleIdList非空，则将该list保存到数据库表中，且admin_id=adminId
        if (roleIdList != null && roleIdList.size() > 0){
            adminMapper.saveAdminRoleRelationship(adminId,roleIdList);
        }
        // roleIdList为空，则清空后不做操作
    }

}


